'use client';

import React, { useState, useEffect } from 'react';
import Calendar from '@/app/components/Calendar';
import BookingForm from '@/app/components/BookingForm';
import TimeSlots from '@/app/components/TimeSlots';
import { supabase } from '@/app/lib/supabase';

interface BookingData {
  name: string;
  phone: string;
  email?: string;
  wechat?: string;
  date: string;
  timeSlot: string;
  notes?: string;
}

const Page: React.FC = () => {
  // 状态管理
  const [selectedDate, setSelectedDate] = useState<string>('');
  const [selectedTimeSlot, setSelectedTimeSlot] = useState<string>('');
  const [bookingData, setBookingData] = useState<BookingData>({
    name: '',
    phone: '',
    email: '',
    wechat: '',
    date: '',
    timeSlot: '',
    notes: ''
  });
  const [isBookingComplete, setIsBookingComplete] = useState<boolean>(false);
  const [step, setStep] = useState<number>(1); // 1: 选择日期, 2: 选择时间, 3: 填写信息
  const [bookedSlots, setBookedSlots] = useState<Record<string, string[]>>({});
  const [loading, setLoading] = useState<boolean>(true);

  // 获取已预约的时间段数据
  const fetchBookedSlots = async () => {
    setLoading(true);
    try {
      const { data, error } = await supabase
        .from('bookings')
        .select('date, time_slot')
        .gte('date', new Date().toISOString().split('T')[0]); // 只获取今天及以后的预约

      if (error) {
        throw error;
      }

      // 转换数据格式为 { date: [timeSlots] }
      const slotsMap: Record<string, string[]> = {};
      if (data) {
        data.forEach(booking => {
          const date = booking.date;
          if (!slotsMap[date]) {
            slotsMap[date] = [];
          }
          slotsMap[date].push(booking.time_slot);
        });
      }

      // 添加一些模拟数据，以便在没有实际预约时也能看到效果
      if (Object.keys(slotsMap).length === 0) {
        slotsMap['2025-09-07'] = ['09:00-09:30', '10:30-11:00', '14:00-14:30'];
        slotsMap['2025-09-08'] = ['11:00-11:30', '15:00-15:30'];
        slotsMap['2025-09-09'] = ['09:30-10:00', '16:00-16:30'];
      }

      setBookedSlots(slotsMap);
    } catch (error) {
      console.error('获取已预约时间段失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 处理日期选择
  const handleDateSelect = (date: string) => {
    setSelectedDate(date);
    setBookingData(prev => ({ ...prev, date }));
    setSelectedTimeSlot('');
    setStep(2);
  };

  // 处理时间段选择
  const handleTimeSlotSelect = (timeSlot: string) => {
    setSelectedTimeSlot(timeSlot);
    setBookingData(prev => ({ ...prev, timeSlot }));
    setStep(3);
  };

  // 在组件加载时获取已预约的时间段
  useEffect(() => {
    fetchBookedSlots();
  }, []);

  // 处理表单输入
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setBookingData(prev => ({ ...prev, [name]: value }));
  };

  // 处理表单提交
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      // 将预约数据保存到Supabase
      const { error } = await supabase
        .from('bookings')
        .insert({
          name: bookingData.name,
          phone: bookingData.phone,
          email: bookingData.email || null,
          wechat: bookingData.wechat || null,
          date: bookingData.date,
          time_slot: bookingData.timeSlot,
          notes: bookingData.notes || null
        });

      if (error) {
        throw error;
      }

      setIsBookingComplete(true);
    } catch (error) {
      console.error('预约失败:', error);
      // 显示错误消息给用户
      alert('预约失败，请稍后重试。');
    }
  };

  // 返回上一步
  const handleBack = () => {
    if (step > 1) {
      setStep(step - 1);
    }
  };

  // 重置预约流程
  const handleReset = () => {
    setStep(1);
    setSelectedDate('');
    setSelectedTimeSlot('');
    setBookingData({
      name: '',
      phone: '',
      email: '',
      wechat: '',
      date: '',
      timeSlot: '',
      notes: ''
    });
    setIsBookingComplete(false);
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-teal-50 to-yellow-50">
      {/* 顶部装饰元素 */}
      <div className="absolute top-0 left-0 w-full h-2 bg-gradient-to-r from-teal-400 via-blue-500 to-yellow-400"></div>
      
      <div className="container mx-auto px-4 py-12 max-w-5xl relative z-10">
        {/* 页面标题 */}
        <header className="text-center mb-12">
          <div className="inline-block mb-4">
            <div className="w-16 h-16 bg-teal-600 rounded-full flex items-center justify-center mx-auto">
              <svg className="w-8 h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
              </svg>
            </div>
          </div>
          <h1 className="text-4xl md:text-5xl font-bold text-teal-700 mb-3 leading-tight">咨询预约系统</h1>
          <p className="text-lg text-teal-600 max-w-2xl mx-auto">简单快捷地安排您的咨询时间，提高工作效率</p>
        </header>

        {/* 预约流程 */}
        <div className="bg-white rounded-2xl shadow-xl p-6 md:p-8 mb-8 transform transition-all duration-300 hover:shadow-2xl">
          {!isBookingComplete ? (
            <>
              {/* 步骤指示器 */}
              <div className="flex justify-center mb-10">
                <div className="flex items-center space-x-6 w-full max-w-2xl">
                  <div className="flex flex-col items-center flex-1">
                    <div className={`w-12 h-12 rounded-full flex items-center justify-center font-bold transition-all duration-300 ${step >= 1 ? 'bg-teal-600 text-white shadow-lg shadow-teal-200' : 'bg-gray-100 text-gray-500'}`}>
                      1
                    </div>
                    <div className="mt-2 text-sm font-medium text-center w-full">
                      <span className={step >= 1 ? 'text-teal-700' : 'text-gray-500'}>选择日期</span>
                    </div>
                  </div>
                  <div className={`h-1 flex-grow transition-all duration-500 ${step >= 2 ? 'bg-teal-600' : 'bg-gray-200'}`}></div>
                  <div className="flex flex-col items-center flex-1">
                    <div className={`w-12 h-12 rounded-full flex items-center justify-center font-bold transition-all duration-300 ${step >= 2 ? 'bg-teal-600 text-white shadow-lg shadow-teal-200' : 'bg-gray-100 text-gray-500'}`}>
                      2
                    </div>
                    <div className="mt-2 text-sm font-medium text-center w-full">
                      <span className={step >= 2 ? 'text-teal-700' : 'text-gray-500'}>选择时间</span>
                    </div>
                  </div>
                  <div className={`h-1 flex-grow transition-all duration-500 ${step >= 3 ? 'bg-teal-600' : 'bg-gray-200'}`}></div>
                  <div className="flex flex-col items-center flex-1">
                    <div className={`w-12 h-12 rounded-full flex items-center justify-center font-bold transition-all duration-300 ${step >= 3 ? 'bg-teal-600 text-white shadow-lg shadow-teal-200' : 'bg-gray-100 text-gray-500'}`}>
                      3
                    </div>
                    <div className="mt-2 text-sm font-medium text-center w-full">
                      <span className={step >= 3 ? 'text-teal-700' : 'text-gray-500'}>填写信息</span>
                    </div>
                  </div>
                </div>
              </div>

              {/* 步骤内容 */}
              <div className="mb-8">
                {step === 1 && (
                  <div className="text-center mb-8">
                    <h2 className="text-2xl font-semibold text-teal-700 mb-4">选择咨询日期</h2>
                    <p className="text-gray-600 mb-8 max-w-md mx-auto">请选择您希望进行咨询的日期，红色标注的日期表示已有预约</p>
                    <div className="max-w-3xl mx-auto">
                      {loading ? (
                        <div className="py-10">
                          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-teal-600 mx-auto mb-4"></div>
                          <p className="text-teal-600">加载中...</p>
                        </div>
                      ) : (
                        <Calendar onDateSelect={handleDateSelect} bookedDates={Object.keys(bookedSlots)} />
                      )}
                    </div>
                  </div>
                )}

                {step === 2 && selectedDate && (
                  <div className="text-center mb-8">
                    <h2 className="text-2xl font-semibold text-teal-700 mb-4">选择咨询时间</h2>
                    <p className="text-gray-600 mb-2">已选择日期: {new Date(selectedDate).toLocaleDateString('zh-CN')}</p>
                    <p className="text-gray-600 mb-8 max-w-md mx-auto">请选择您希望进行咨询的时间段，每30分钟一个时段</p>
                    <div className="max-w-3xl mx-auto">
                      <TimeSlots 
                        date={selectedDate} 
                        bookedSlots={bookedSlots[selectedDate] || []} 
                        onTimeSlotSelect={handleTimeSlotSelect} 
                      />
                    </div>
                  </div>
                )}

                {step === 3 && selectedDate && selectedTimeSlot && (
                  <div className="mb-8">
                    <h2 className="text-2xl font-semibold text-teal-700 mb-6 text-center">填写个人信息</h2>
                    <div className="max-w-2xl mx-auto">
                      <BookingForm 
                        bookingData={bookingData} 
                        onInputChange={handleInputChange} 
                        onSubmit={handleSubmit} 
                      />
                    </div>
                  </div>
                )}
              </div>

              {/* 导航按钮 */}
              <div className="flex justify-between max-w-2xl mx-auto">
                {step > 1 && (
                  <button 
                    onClick={handleBack} 
                    className="px-8 py-3 bg-gray-100 hover:bg-gray-200 text-gray-800 rounded-xl transition-all duration-300 transform hover:scale-[1.02] active:scale-[0.98] shadow-sm"
                  >
                    上一步
                  </button>
                )}
                {step < 3 && (
                  <button 
                    disabled={
                      (step === 1 && !selectedDate) || 
                      (step === 2 && !selectedTimeSlot)
                    }
                    className={`px-8 py-3 rounded-xl transition-all duration-300 transform hover:scale-[1.02] active:scale-[0.98] font-medium ml-auto shadow-sm
                      ${(
                        (step === 1 && !selectedDate) || 
                        (step === 2 && !selectedTimeSlot)
                      ) ? 'bg-gray-300 text-gray-500 cursor-not-allowed' : 'bg-teal-600 hover:bg-teal-700 text-white shadow-md hover:shadow-lg'}`}
                    onClick={() => step < 3 && setStep(step + 1)}
                  >
                    下一步
                  </button>
                )}
              </div>
            </>
          ) : (
            // 预约成功页面
            <div className="text-center py-10">
              <div className="w-24 h-24 bg-teal-100 rounded-full flex items-center justify-center mx-auto mb-8">
                <svg className="w-12 h-12 text-teal-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                </svg>
              </div>
              <h2 className="text-3xl font-semibold text-teal-700 mb-4">预约成功！</h2>
              <p className="text-gray-600 mb-8 max-w-md mx-auto">您的咨询预约已成功提交，我们会尽快与您联系确认详情。</p>
              <div className="bg-teal-50 p-6 rounded-xl text-left max-w-md mx-auto mb-8 shadow-sm border border-teal-100">
                <h3 className="font-semibold text-teal-700 mb-4">预约信息</h3>
                <div className="space-y-3">
                  <p><span className="font-medium text-teal-700">姓名:</span> <span className="ml-2 text-gray-700">{bookingData.name}</span></p>
                  <p><span className="font-medium text-teal-700">电话:</span> <span className="ml-2 text-gray-700">{bookingData.phone}</span></p>
                  {bookingData.email && <p><span className="font-medium text-teal-700">邮箱:</span> <span className="ml-2 text-gray-700">{bookingData.email}</span></p>}
                  {bookingData.wechat && <p><span className="font-medium text-teal-700">微信:</span> <span className="ml-2 text-gray-700">{bookingData.wechat}</span></p>}
                  <p><span className="font-medium text-teal-700">日期:</span> <span className="ml-2 text-gray-700">{new Date(bookingData.date).toLocaleDateString('zh-CN')}</span></p>
                  <p><span className="font-medium text-teal-700">时间:</span> <span className="ml-2 text-gray-700">{bookingData.timeSlot}</span></p>
                  {bookingData.notes && <p><span className="font-medium text-teal-700">备注:</span> <span className="ml-2 text-gray-700">{bookingData.notes}</span></p>}
                </div>
              </div>
              <button 
                onClick={handleReset} 
                className="px-8 py-4 bg-teal-600 hover:bg-teal-700 text-white rounded-xl transition-all duration-300 transform hover:scale-[1.02] active:scale-[0.98] shadow-lg hover:shadow-xl"
              >
                返回首页
              </button>
            </div>
          )}
        </div>

        {/* 页脚 */}
        <footer className="text-center text-gray-500 text-sm mt-12">
          <p className="mb-2">© 2025 咨询预约系统. 保留所有权利.</p>
          <div className="flex justify-center space-x-4 text-xs">
            <a href="#" className="hover:text-teal-600 transition-colors">隐私政策</a>
            <a href="#" className="hover:text-teal-600 transition-colors">使用条款</a>
            <a href="#" className="hover:text-teal-600 transition-colors">联系我们</a>
          </div>
        </footer>
      </div>
    </div>
  );
};

export default Page;